package com.dong.es.config;

import com.dong.es.service.EsService;
import com.dong.es.service.impl.EsServiceImpl;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @description:
 * @author: 陈瑞东
 * @create: 2022-12-09 11:27
 */
@Configuration
@EnableConfigurationProperties(EsProperties.class)
public class EsAutoConfiguration {

    private EsProperties properties;

    public EsAutoConfiguration(EsProperties properties) {
        this.properties = properties;
    }

    @Bean
    @ConditionalOnMissingBean
    public EsClientPoolFactory esClientPoolFactory(){
        EsClientPoolFactory esClientPoolFactory = new EsClientPoolFactory();
        // 设置ES的地址
        esClientPoolFactory.setHttpList(properties.getHosts());
        // 设置用户名
        esClientPoolFactory.setUsername(properties.getUsername());
        // 设置密码
        esClientPoolFactory.setPassword(properties.getPassword());
        // 设置是否是SSL
        esClientPoolFactory.setSSL(properties.isSsl());
        return esClientPoolFactory;
    }

    @Bean
    @ConditionalOnMissingBean
    public EsClientPool esConnectionPool(EsClientPoolFactory esClientPoolFactory) {
        GenericObjectPoolConfig poolConfig = new GenericObjectPoolConfig();
        poolConfig.setMaxTotal(8);
        EsClientPool genericObjectPool = new EsClientPool(esClientPoolFactory, poolConfig);
        return genericObjectPool;
    }

    @Bean
    @ConditionalOnMissingBean
    public EsService esService() {
        return new EsServiceImpl();
    }

}
